package server.request;


import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.HttpContent;
import io.netty.handler.codec.http.HttpObject;
import server.netty.ChannelRequestHandler;
import server.response.HttpResponse;
import server.servlet.HttpServlet;

import java.util.Map;

/**
 * @author cg
 * @date 2023/6/12 9:54
 */
public class RequestProcessor extends SimpleChannelInboundHandler<HttpObject> {

    private Map<String, HttpServlet> httpServletMap;
    public RequestProcessor(Map<String, HttpServlet> httpServletMap) {
        this.httpServletMap = httpServletMap;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        Channel channel = ctx.channel();
        if (msg instanceof io.netty.handler.codec.http.HttpRequest) {

            //收到http请求，解析为自己的request
            HttpRequest request = new HttpRequest(ctx,msg);
            ChannelRequestHandler.setRequest(channel, request);
        }
        if (msg instanceof HttpContent) {
            try {
                HttpRequest request = ChannelRequestHandler.getRequest(channel);
                //获取请求体数据
                request.setRequestBodyMap(msg);
                //解析自己的response
                HttpResponse response = new HttpResponse(ctx, msg);
                //执行请求处理
                doProcessor(request, response);
            } finally {
                ChannelRequestHandler.removeChannel(channel);
            }
        }
    }

    private void doProcessor(HttpRequest httpRequest, HttpResponse httpResponse) {
        try {
            String url = httpRequest.getUrl();
            String match = match(url);
            if (!"".equals(match)) {
                //交给对应的servlet来处理
                HttpServlet httpServlet = httpServletMap.get(match);
                httpServlet.service(httpRequest, httpResponse);
                //执行销毁操作
                httpServlet.destroy();
            } else {
                httpResponse.writeResource(url);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private String match(String url) {
        int len = url.length();
        for (String pattern : httpServletMap.keySet()) {
            int length = pattern.length();
            boolean isValid = true;
            for (int i = 0; i < length && i < len; i++) {
                char ch1 = url.charAt(i);
                char ch2 = pattern.charAt(i);
                if ('*' == ch2 && url.charAt(i - 1) == '/') return pattern;
                if (ch1 != ch2) {
                    isValid = false;
                    break;
                }
            }
            if (isValid) return pattern;
        }
        return "";
    }

}
